package cn.qinhao.pethome.login.service.impl;

import cn.qinhao.pethome.basic.base.BaseConstants;
import cn.qinhao.pethome.basic.exception.BusinessException;
import cn.qinhao.pethome.basic.until.MD5Utils;
import cn.qinhao.pethome.basic.until.StrUtils;
import cn.qinhao.pethome.login.domain.RegisterVo;
import cn.qinhao.pethome.login.service.RegisterService;
import cn.qinhao.pethome.org.domain.User;
import cn.qinhao.pethome.org.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RedisTemplate  redisTemplate;
    @Autowired//注入业务层都是为了数据同步，重写方法都到用户业务层去添加逻辑
    private IUserService userService;
    @Override
    public void userRegister(RegisterVo registerVo) {
        //1、校验参数
        //校验手机号不能为空
        if(registerVo.getMobile()==null){
            throw new BusinessException("手机号不能为空");
        }
        //校验短信验证码不能为空
        if(registerVo.getMobileCode()==null){
            throw new BusinessException("短信验证码不能为空");
        }
        //校验密码不能为空
        if(registerVo.getPassword()==null){
            throw new BusinessException("密码不能为空");
        }
        //校验重设密码不能为空
        if(registerVo.getPasswordRepeat()==null){
            throw new BusinessException("重设密码不能为空");
        }
        //校验两次输入密码是否一致
        if(!registerVo.getPassword().equals(registerVo.getPasswordRepeat())){
            throw new BusinessException("两次输入密码不一致，请重新输入");
        }
        //2、校验手机验证码
        Object smsCode = redisTemplate.opsForValue().get(registerVo.getMobile()+BaseConstants.ImgCode.STATE_REGISTER);
        if(smsCode==null){//注意，为空最好不要调用，防止空指针
            throw new BusinessException("短信验证码已经过期，请你重新获取");
        }
        //不为空就判断输入和保存的验证码是否一致
        if(!smsCode.toString().equals(registerVo.getMobileCode())){
            throw new BusinessException("短信验证码输入错误，请重新输入");
        }
        //3、保存数据
            User user = new User();
        user.setCreatetime(new Date());
        //密码得加密加盐(使用数字加字母得方式获取)
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(registerVo.getPassword() + salt);
        user.setSalt(salt);//方便以后用盐值去比对
        user.setPassword(saltPassword);
        user.setUsername(registerVo.getMobile());
        user.setPhone(registerVo.getMobile());
        user.setAge(0);//设置默认值，用户自己去改
        user.setState(BaseConstants.User.STATE_NORMAL);
        userService.add(user);
    }
}
